package com.h3c.web.rest;

import java.sql.SQLException;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.h3c.dal.common.TableConstant;
import com.h3c.dal.dao.CasssoDeptDAO;
import com.h3c.dal.dao.CasssoDeptUserRelationDAO;
import com.h3c.dal.dao.CasssoUserDAO;
import com.h3c.dal.entity.CasssoDeptDO;
import com.h3c.dal.entity.CasssoDeptUserRelationDO;
import com.h3c.dal.entity.CasssoUserDO;
import com.h3c.dal.entity.query.CasssoDeptQuery;
import com.h3c.dal.entity.query.CasssoDeptUserRelationQuery;
import com.h3c.dal.entity.query.CasssoUserQuery;
import com.h3c.web.common.BaseResponse;
import com.h3c.web.common.ErrorMsgEnum;
import com.h3c.web.common.helper.UserHelper;
import com.h3c.web.common.utils.BeanUtil;
import com.h3c.web.common.utils.BindingResultUtil;
import com.h3c.web.common.utils.ListUtil;
import com.h3c.web.common.utils.UUIDUtil;
import com.h3c.web.common.vo.CasssoDeptVO;
import com.h3c.web.common.vo.CasssoUserVO;

/**
 * @ClassName: DeptRest
 * @Description: 部门restapi
 * @author: d14287
 * @date: 2017年5月31日 下午3:43:41
 */
@Controller
@RequestMapping("console/dept")
public class DeptRest {
	public static final Logger logger = LoggerFactory.getLogger(DeptRest.class);
	@Autowired
	private CasssoDeptDAO casssoDeptDAO;
	@Autowired
	private CasssoDeptUserRelationDAO casssoDeptUserRelationDAO;
	@Autowired
	private CasssoUserDAO casssoUserDAO;

	/**
	 */
	@RequestMapping(value = "/add.ajax", method = RequestMethod.POST)
	public @ResponseBody
	BaseResponse add(@RequestBody @Valid CasssoDeptVO deptVO,
			BindingResult bindingResult) throws Exception {
		if (bindingResult.hasErrors()) {
			return BaseResponse.falseOf(BindingResultUtil
					.assembleErrMsg(bindingResult));
		}
		CasssoDeptDO deptDO = new CasssoDeptDO();
		BeanUtil.copyProperties(deptVO, deptDO);
		deptDO.setDeptId(UUIDUtil.generateUUID());
		deptDO.setCreater(UserHelper.get());
		deptDO.setCreateTime(new Date());
		deptDO.setCreater(UserHelper.get());
		deptDO.setStatus(TableConstant.COMMON_STATUS_NORMAL);
		deptDO.setParentId(StringUtils.isBlank(deptDO.getParentId()) ? null
				: deptDO.getParentId());
		casssoDeptDAO.insert(deptDO);
		return BaseResponse.trueOf();
	}

	@RequestMapping(value = "/delete.ajax", method = RequestMethod.GET)
	public @ResponseBody
	BaseResponse delete(@RequestParam("deptId") String deptId) throws Exception {
		if (StringUtils.isBlank(deptId)) {
			return BaseResponse.falseOf(ErrorMsgEnum.deptId_cannot_blank
					.getMsg());
		}
		// 查询子部门
		List<CasssoDeptDO> subDept = queryDirectSubDept(deptId);
		if (!ListUtil.isEmpty(subDept)) {
			return BaseResponse.falseOf(ErrorMsgEnum.dept_cannot_delete
					.getMsg());
		}
		// 查询用户
		List<CasssoDeptUserRelationDO> deptUserList = queryDirectDeptUser(deptId);
		if (!ListUtil.isEmpty(deptUserList)) {
			return BaseResponse.falseOf(ErrorMsgEnum.dept_cannot_delete
					.getMsg());
		}
		CasssoDeptDO deptDO = new CasssoDeptDO();
		deptDO.setDeptId(deptId);
		deptDO.setStatus(TableConstant.COMMON_STATUS_DELETE);
		casssoDeptDAO.updateByPrimaryKeySelective(deptDO);
		return BaseResponse.trueOf();
	}

	@RequestMapping(value = "/edit.ajax", method = RequestMethod.POST)
	public @ResponseBody
	BaseResponse update(@RequestBody @Valid CasssoDeptVO deptVO,
			BindingResult bindingResult) throws Exception {
		if (bindingResult.hasErrors()) {
			return BaseResponse.falseOf(BindingResultUtil
					.assembleErrMsg(bindingResult));
		}
		// 一定不能将父部门置于子部门树下
		List<String> subDeptIds = Lists.newArrayList();
		queryAllSubDeptId(deptVO.getDeptId(), subDeptIds);
		if (subDeptIds.contains(deptVO.getParentId())) {
			return BaseResponse
					.falseOf(ErrorMsgEnum.parentdept_cannot_place_under_subdept
							.getMsg());
		}
		CasssoDeptDO deptDO = new CasssoDeptDO();
		BeanUtil.copyProperties(deptVO, deptDO);
		casssoDeptDAO.updateByPrimaryKeySelective(deptDO);
		return BaseResponse.trueOf();
	}

	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/fuzzyQuery.ajax", method = RequestMethod.GET)
	public @ResponseBody
	BaseResponse query(@RequestParam("key") String key) throws Exception {
		CasssoDeptQuery query = new CasssoDeptQuery();
		query.createCriteria().andNameLike("%" + key + "%");
		List<CasssoDeptDO> deptList = casssoDeptDAO.selectByExample(query);
		return BaseResponse.trueOf(deptList);
	}

	@RequestMapping(value = "/querydeptTree.ajax", method = RequestMethod.GET)
	public @ResponseBody
	BaseResponse querydepTree(@RequestParam("ouId") String ouId)
			throws Exception {
		List<CasssoDeptVO> result = queryOuDept(ouId);
		return BaseResponse.trueOf(result);
	}

	/**
	 * 查询所有组织下的一级部门
	 * 
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	public List<CasssoDeptDO> queryHighDept(HttpServletRequest request)
			throws Exception {
		CasssoDeptQuery query = new CasssoDeptQuery();
		query.createCriteria().andParentIdIsNull()
				.andStatusEqualTo(TableConstant.COMMON_STATUS_NORMAL);
		List<CasssoDeptDO> deptList = casssoDeptDAO.selectByExample(query);
		return deptList;
	}

	/**
	 * 查询子部门
	 * 
	 * @param parentId
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/querysub.ajax", method = RequestMethod.GET)
	public @ResponseBody
	BaseResponse querySubDept(@RequestParam("parentId") String parentId,
			HttpServletRequest request) throws Exception {
		List<CasssoDeptDO> subDeptList = queryDirectSubDept(parentId);

		return BaseResponse.trueOf(ListUtil.copyList(subDeptList,
				CasssoDeptVO.class));
	}

	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/pageQueryUser.ajax", method = RequestMethod.GET)
	public @ResponseBody BaseResponse queryDetpUser(@RequestParam("deptId") String deptId,
			@RequestParam("pageIndex") Integer pageIndex, HttpServletRequest request) throws Exception {
		CasssoDeptUserRelationQuery query = new CasssoDeptUserRelationQuery();
		query.createCriteria().andDeptIdEqualTo(deptId).andStatusEqualTo(TableConstant.COMMON_STATUS_NORMAL);
		query.setPageSize(5);
		query.setPageIndex(pageIndex);
		List<CasssoDeptUserRelationDO> deptUserList = casssoDeptUserRelationDAO.pageSelectByExample(query);
		List<String> userIds = Lists.newArrayList();
		deptUserList.forEach(deptUser -> userIds.add(deptUser.getDeptId()));
		CasssoUserQuery userExample = new CasssoUserQuery();
		userExample.createCriteria().andUserIdIn(userIds).andStatusEqualTo(TableConstant.COMMON_STATUS_NORMAL);
		List<CasssoUserDO> userList = casssoUserDAO.selectByExample(userExample);
		Map<String, Object> data = Maps.newHashMap();
		data.put("totalPage", query.getPageCount());
		data.put("pageIndex", query.getPageIndex());
		data.put("userList", ListUtil.copyList(userList, CasssoUserVO.class));
		data.put("total", query.getCount());
		return BaseResponse.trueOf(data);
	}

	/**
	 * 查询组织部门树
	 * 
	 * @param ouId
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	public List<CasssoDeptVO> queryOuDept(String ouId) throws Exception {
		CasssoDeptQuery query = new CasssoDeptQuery();
		query.createCriteria().andParentIdIsNull()
				.andStatusEqualTo(TableConstant.COMMON_STATUS_NORMAL)
				.andOutIdEqualTo(ouId);
		List<CasssoDeptDO> deptList = casssoDeptDAO.selectByExample(query);
		if (ListUtil.isEmpty(deptList))
			return Lists.newArrayList();
		List<CasssoDeptVO> deptVOs = Lists.newArrayList();
		for (CasssoDeptDO casssoDeptDO : deptList) {
			CasssoDeptVO deptVO = new CasssoDeptVO();
			BeanUtil.copyProperties(casssoDeptDO, deptVO);
			queryAllSubDept(deptVO);
			deptVOs.add(deptVO);
		}
		return deptVOs;
	}

	/**
	 * 查询直接下属部门
	 * 
	 * @param parentId
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public List<CasssoDeptDO> queryDirectSubDept(String deptId) {
		CasssoDeptQuery query = new CasssoDeptQuery();
		query.createCriteria().andParentIdEqualTo(deptId)
				.andStatusEqualTo(TableConstant.COMMON_STATUS_NORMAL);
		List<CasssoDeptDO> result = null;
		try {
			result = casssoDeptDAO.selectByExample(query);
		} catch (SQLException e) {
			logger.error(e.getMessage());
		}
		return result;
	}

	/**
	 * 查询所有下属部门树
	 * 
	 * @param result
	 * @param parentId
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	public void queryAllSubDept(CasssoDeptVO parent) throws Exception {
		List<CasssoDeptDO> subDepts = queryDirectSubDept(parent.getDeptId());
		if (ListUtil.isEmpty(subDepts)) {
			return;
		}
		List<CasssoDeptVO> subDeptVOs = ListUtil.copyList(subDepts,
				CasssoDeptVO.class);
		parent.setSubDeptList(subDeptVOs);
		for (CasssoDeptVO subDeptVO : subDeptVOs) {
			queryAllSubDept(subDeptVO);
		}
	}

	/**
	 * 查询直接部门用户
	 * 
	 * @param deptId
	 * @return
	 * @throws SQLException
	 */
	@SuppressWarnings("unchecked")
	public List<CasssoDeptUserRelationDO> queryDirectDeptUser(String deptId)
			throws SQLException {
		CasssoDeptUserRelationQuery query = new CasssoDeptUserRelationQuery();
		query.createCriteria().andDeptIdEqualTo(deptId)
				.andStatusEqualTo(TableConstant.COMMON_STATUS_NORMAL);
		List<CasssoDeptUserRelationDO> deptUserList = casssoDeptUserRelationDAO
				.selectByExample(query);
		return deptUserList;
	}

	/**
	 * @Desc: 查询所有子部门id
	 * @param deptId
	 * @return
	 * @return: List<String>
	 */
	public void queryAllSubDeptId(String deptId, List<String> subDeptIds) {
		List<CasssoDeptDO> subDepts = queryDirectSubDept(deptId);
		if (ListUtil.isEmpty(subDepts)) {
			return;
		}
		subDepts.forEach(subDept -> {
			subDeptIds.add(subDept.getDeptId());
			queryAllSubDeptId(subDept.getDeptId(), subDeptIds);
		});
	}
}
